<template>
  <div class="app-container">

    <div style="margin-left:20px">
      <el-form ref="queryForm" label-position="left" label-width="70px" inline size="small" >
        <el-form-item label="" >
          <el-input v-model="queryInfo" style="width: 300px;" placeholder="请输入字典类型或字典值" @keyup.enter.native="queryClick"/>
        </el-form-item>
        <el-form-item label="" >
          <el-button type="primary" @click="queryClick">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <data-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      :border="false"
      :stripe="true"
      url="/dic/list"
      size="small"
      style="width: 100%;"
      @filter-change="handleFilterChange">

      <el-table-column label="编号" prop="ID" align="center" width="100px"/>
      <el-table-column :filters="typeFilters" label="字典类型" filter-placement="bottom" column-key="TypeID" prop="TypeName" align="center" min-width="120px"/>
      <el-table-column :filters="[{'text':'是','value':true},{'text':'否','value':false}]" label="只读" prop="IsReadOnly" filter-placement="bottom" column-key="IsReadOnly" align="center" width="100px">
        <template slot-scope="scope" >
          <span>{{ scope.row.IsReadOnly ?"是":'否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="字典Key" prop="DKey" align="center" width="100px"/>
      <el-table-column label="字典值" prop="DValue" align="center" min-width="100px" />
      <el-table-column label="备注" prop="Comment" align="center" min-width="100px" />
      <el-table-column v-if="canEdit" label="操作" align="center" width="100px" class-name="small-padding fixed-width" >
        <template slot="header" slot-scope="scope">
          <el-button v-if="canAdd" type="text" size="mini" @click="handleCreate">添加</el-button>
          <template v-else>{{ scope.column.label }}</template>
        </template>
        <template slot-scope="scope" >
          <el-button v-if="!scope.row.IsReadOnly && canUpdate" type="text" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <confirm-poptip v-if="!scope.row.IsReadOnly && canDelete" type="text" size="mini" @on-ok="handleDelete(scope.row)"/>
        </template>
      </el-table-column>
    </data-table>

    <div class="pagination-container">
      <el-pagination :current-page="listQuery.page" :page-sizes="[10,15,20,30, 50]" :disabled="listLoading" :page-size="listQuery.limit" :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>

    <el-dialog v-el-drag-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="600px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" size="small" >

        <el-form-item label="字典类型：" prop="TypeID">
          <el-select v-model="temp.TypeID" :disabled="dialogStatus == 'update'" filterable class="filter-item" style="width:100%">
            <el-option v-for="item in typeList" :key="item.TypeID" :label="item.TypeName" :value="item.TypeID"/>
          </el-select>
        </el-form-item>
        <el-form-item label="字典Key：" prop="DKey">
          <el-input-number v-model="temp.DKey" :disabled="dialogStatus == 'update'" :precision="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="字典值：" prop="DValue">
          <el-input v-model="temp.DValue" :maxlength="20"/>
        </el-form-item>
        <el-form-item label="备注：" prop="Comment">
          <el-input v-model="temp.Comment" :maxlength="50" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" :loading="okloading" type="primary" @click="createData">确 定</el-button>
        <el-button v-else :loading="okloading" type="primary" @click="updateData">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getList, getTypeData, getInfo, add, update, remove } from '@/api/dic'
import waves from '@/directive/waves' // 水波纹指令
import { canAdd, canUpdate, canDelete } from '@/utils'
import elDragDialog from '@/directive/el-dragDialog'

export default {
  name: 'Dic',
  directives: { waves, elDragDialog },
  filters: {
  },
  data() {
    return {
      controllerName: 'Dic',
      okloading: false,
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      typeData: [],
      typeList: [],
      editTypeList: [],
      typeFilters: [],
      listQuery: {
        page: 1,
        limit: 15,
        filters: []
      },
      queryInfo: null,
      temp: {
        ID: null,
        TypeID: null,
        DKey: null,
        DValue: '',
        Comment: ''
      },
      filters: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新建'
      },
      rules: {
        ID: { required: false, message: '不能为空' },
        TypeID: { required: true, message: '不能为空' },
        DKey: { required: true, message: '不能为空' },
        DValue: { required: true, message: '不能为空' },
        Comment: { required: false, message: '不能为空' }

      }
    }
  },

  computed: {
    canEdit() {
      return this.canAdd || this.canUpdate || this.canDelete
    },
    canAdd() {
      return canAdd(this.$store.state, this.controllerName)
    },
    canUpdate() {
      return canUpdate(this.$store.state, this.controllerName)
    },
    canDelete() {
      return canDelete(this.$store.state, this.controllerName)
    }
  },
  watch: {
  },
  created() {
    this.getType()
    this.getList()
  },
  methods: {

    handleFilterChange(filters) {
      let row = null
      let val = null
      for (const i in filters) {
        row = i
        val = filters[i]
      }
      const filter = [{
        row: row,
        op: 'contains',
        value: val
      }]
      this.setFilter(filter)
    },

    setFilter(filters) {
      for (const i in filters) {
        let filter = null
        for (const j in this.filters) {
          if (filters[i]['row'] === this.filters[j]['row']) {
            filter = this.filters[j]
          }
        }
        if (filter == null) {
          this.filters.push({ 'row': filters[i].row, 'op': filters[i].op, 'value': filters[i].value })
        } else {
          filter.value = filters[i].value
          filter.op = filters[i].op
        }
      }

      this.listQuery.page = 1
      this.getList()
    },

    getType() {
      getTypeData().then(response => {
        this.typeData = response.data

        this.editTypeList = this.typeData.filter((info) => info.IsReadOnly === false)
        this.setTypeFilters()
      })
    },

    setTypeFilters() {
      const data = this.typeData
      const temp = []
      for (let i = 0; i < data.length; i++) {
        const name = data[i].TypeName
        const id = data[i].TypeID
        temp.push({ text: name, value: id })
      }
      this.typeFilters = temp
    },

    getList() {
      this.listLoading = true
      const filters = []
      for (const i in this.filters) {
        if (this.filters[i].value && this.filters[i].value.length > 0) {
          filters.push({ 'field': this.filters[i].row, 'op': this.filters[i].op, 'value': this.filters[i].value })
        }
      }
      if (filters.length > 0) {
        this.listQuery.filters = JSON.stringify(filters)
      } else {
        this.listQuery.filters = null
      }
      this.listQuery.query = this.queryInfo
      getList(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.total
        this.listLoading = false
      })
    },

    queryClick() {
      this.listQuery.page = 1
      this.getList()
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetTemp() {
      this.temp = {
        ID: null,
        TypeID: null,
        DKey: null,
        DValue: '',
        Comment: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.typeList = this.editTypeList
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.okloading = true
          const mytemp = Object.assign({}, this.temp)

          add(mytemp).then((response) => {
            this.okloading = false
            if (response.data) {
              const mydata = response.data
              this.temp = mydata
            }
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          }).catch(() => {
            this.okloading = false
          })
        }
      })
    },
    handleUpdate(row) {
      const mydata = Object.assign({}, row)
      this.temp = mydata
      this.dialogStatus = 'update'
      this.typeList = this.typeData
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      getInfo(row.ID).then((response) => {
        if (response.success) {
          const data = response.data
          this.temp = Object.assign({}, data)

          for (const v of this.list) {
            if (v.ID === data.ID) {
              const index = this.list.indexOf(v)
              this.list.splice(index, 1, data)
              break
            }
          }
        }
      })
    },

    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.okloading = true
          const mytemp = Object.assign({}, this.temp)
          update(mytemp).then((response) => {
            this.okloading = false
            if (response.data) {
              const mydata = response.data
              this.temp = mydata
            }
            for (const v of this.list) {
              if (v.ID === this.temp.ID) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          }).catch(() => {
            this.okloading = false
          })
        }
      })
    },
    handleDelete(row) {
      remove(row.ID).then((response) => {
        if (response.success) {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        }
      })
    }

  }
}

</script>
